#!/usr/bin/env bash
set -e # 这告诉bash一但有任何一个语句返回非真的值，则退出bash。

PROG_NAME=`basename $0`
PROG_DIR=`dirname $0`
PROG_DIR=`cd "$PROG_DIR" && pwd`

. "$PROG_DIR/vic/log.sh"

function print_help {
    echo -e "Usage: $PROG_NAME [options] [path]"
    echo -e ""
    echo -e "Options:"
    echo -e "  -b, --bytes"
    echo -e "    Print the byte counts."
    echo -e ""
    echo -e "  -c, --chars"
    echo -e "    Print the character counts."
    echo -e ""
    echo -e "  --cpp"
    echo -e "    Find c, c++ source file."
    echo -e ""
    echo -e "  --csharp"
    echo -e "    Find csharp source file."
    echo -e ""
    echo -e "  --go"
    echo -e "    Find go source file."
    echo -e ""
    echo -e "  --java"
    echo -e "    Find java source file."
    echo -e ""
    echo -e "  -l, --lines"
    echo -e "    Print the newline counts."
    echo -e ""
    echo -e "  --lua"
    echo -e "    Find lua source file."
    echo -e ""
    echo -e "  -n NAME, --name=NAME"
    echo -e "    Find file name."
    echo -e ""
    echo -e "  --python"
    echo -e "    Find python source file."
    echo -e ""
    echo -e "  -w, --words"
    echo -e "    Print the word counts."
    echo -e ""
    echo -e "  -h, --help"
    echo -e "    Displays help message."
    echo -e ""
}

CMD_GETOPT=`getopt -o bchln:w --long bytes,chars,cpp,csharp,go,java,lines,lua,name:,python,words,help -n 'example.bash' -- "$@"`
eval set -- "$CMD_GETOPT"

function append_find_name {
    for ARG in "$@"
    do
        if [[ -n $FIND_NAME ]] ; then
            FIND_NAME="$FIND_NAME -n \"$ARG\""
        else
            FIND_NAME="-n \"$ARG\""
        fi
    done
}

function append_wc_args {
    for ARG in "$@"
    do
        if [[ -n $WC_ARGS ]] ; then
            WC_ARGS="$WC_ARGS $ARG"
        else
            WC_ARGS="$ARG"
        fi
    done
}

while true ; do
    case "$1" in
        -b|--bytes) append_wc_args "--bytes"; shift ;;
        -c|--chars) append_wc_args "--chars"; shift ;;
        --cpp) append_find_name "*.h" "*.hpp" "*.c" "*.cc" "*.cpp"; shift ;;
        --csharp) append_find_name "*.cs"; shift ;;
        --go) append_find_name "*.go"; shift ;;
        --java) append_find_name "*.java"; shift ;;
        -l|--lines) append_wc_args "--lines"; shift ;;
        --lua) append_find_name "*.lua"; shift ;;
        -n|--name) append_find_name "$2" ; shift 2 ;;
        --python) append_find_name "*.py"; shift ;;
        -w|--words) append_wc_args "--words"; shift ;;
        -h|--help) print_help; exit 1 ;;
        --) shift; break ;;
        *) echo "Unknown option: $1"; print_help; exit 1 ;;
    esac
done

for arg do
    FIND_PATH="$FIND_PATH $arg"
done

EXP="find.sh $FIND_PATH -t f $FIND_NAME | xargs wc $WC_ARGS"
vic_log_debug "EXP: $EXP"
eval $EXP
